package com.hzsai.handler;

import com.hzsai.utils.LineToHumpUtils;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 将结果集转换成bean对象的list集合的处理器
 * @Author suzhenyin
 * @Date 2019/4/23 9:48
 * @Version 1.0
 **/
public class BeanListHandler implements ResultSetHandler {
    private Class<?> clazz;

    public BeanListHandler(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    public Object handler(ResultSet rs) {
        try {
            List<Object> list = new ArrayList<Object>();
            while (rs.next()) {
                Object bean = clazz.newInstance();
                ResultSetMetaData metadata = rs.getMetaData();
                int count = metadata.getColumnCount();
                for (int i = 0; i < count; i++) {
                    String name = metadata.getColumnLabel(i + 1);
                    //System.out.println("getColumnLabel:  " + metadata.getColumnLabel(i + 1));
                    Object value = rs.getObject(name);
                    String newCoulmnName = LineToHumpUtils.lineToHump(name);
                    Field f = bean.getClass().getDeclaredField(newCoulmnName);
                    f.setAccessible(true);
                    f.set(bean, value);
                }
                list.add(bean);
            }
            return list.size() > 0 ? list : null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
